//
//  SendBookViewController.swift
//  微博
//
//  Created by mac on 15/12/23.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD

class SendBookViewController: UIViewController {
    //选中图片
    @objc private func selectPicture() {
        print(__FUNCTION__)
        //让键盘失去第一响应者
        textView.resignFirstResponder()
        //设置图片的选择器
        addPictureVC.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(screenHeight / 3 * 2)
        }
        UIView.animateWithDuration(0.25) { () -> Void in
            //强制刷新
            self.view.layoutIfNeeded()
        }
        
    }
    //选则表情
    @objc private func selectEmoticonKeyboard() {
        print(__FUNCTION__)
        //失去第一响应者
        textView.resignFirstResponder()
        textView.inputView = textView.inputView == nil ?  EmoticonBoardView : nil
        textView.becomeFirstResponder()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //设置UI
        setupUI()
    }
    //成为第一响应者
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if addPictureVC.imageList.count == 0 {
            textView.becomeFirstResponder()
        }
    }
    
       //添加发送的方法
    @objc private func send() {
        //URL
        var urlstr = "2/statuses/update.json"
        guard let token = UserAccontViewMedol().token else {
            SVProgressHUD.showWithStatus("请重新登录")
            return
        }
        let parameters = ["access_token":token ,"status":textView.imageTextViewToText() ?? ""]
        //发送网络请求
        if addPictureVC.imageList.count != 0 {
            urlstr = "https://upload.api.weibo.com/2/statuses/upload.json"
            let imageData = UIImagePNGRepresentation(addPictureVC.imageList.first!)
            NetworkTools.sharedTools.setImageData(urlstr, parameters: parameters, imageData: imageData!, finished: { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showWithStatus("发送失败,请检查网络")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发送成功")
                self.close()
            })
        }else{
            NetworkTools.sharedTools.requestJSONDict(.POST, urlString: urlstr, parameters:parameters) { (result, error) -> () in
                if error != nil {
                    SVProgressHUD.showWithStatus("发送失败,请检查网络")
                    return
                }
                SVProgressHUD.showSuccessWithStatus("发送成功")
                self.close()
            }
        }
    }
    //添加关闭的方法
    @objc private func close(){
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //析构函数
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //懒加载视图
    private lazy var EmoticonBoardView: EmoticonBoard = EmoticonBoard { [weak self](em) -> () in
        //点击事件来触发返回的事件
        self?.textView.insertEmoticon(em)
    }
    private lazy var textView:EmoticonTextView = {
        let tv = EmoticonTextView()
//        tv.text = "输入新鲜事"
        tv.font = UIFont.systemFontOfSize(18)
        tv.backgroundColor = UIColor.randomColor()
        tv.alwaysBounceVertical = true
        tv.keyboardDismissMode = .OnDrag
        tv.delegate = self
        return tv
    }()
    private lazy var placeLabel:UILabel = UILabel(content: "输入新鲜事", color: UIColor.lightGrayColor(), fontSize: 18)
    private lazy var toolBar:UIToolbar = UIToolbar()
    
    private lazy var addPictureVC:AddPictureViewController = AddPictureViewController()
}
//textView代理方法
extension SendBookViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        //当发生改变的时候就会调用
            navigationItem.rightBarButtonItem?.enabled = textView.hasText()
            placeLabel.hidden = textView.hasText()
    }
}

extension SendBookViewController {
    private func setupUI() {
        //设置颜色
        view.backgroundColor = UIColor.whiteColor()
        setTextView()
        setNav()
        setToolBar()
        setPicture()
        //注册通知
        registerNotification()
    }
    //设置图片选择控制器
    private func setPicture() {
        //添加选择图片控制器
        addChildViewController(addPictureVC)
        //添加视图
        view.addSubview(addPictureVC.view)
        //讲toolbar移到最上面的图层
        view.bringSubviewToFront(toolBar)
        //设置frame
        addPictureVC.view.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(0)
        }
    }
    
    //设置toolBar
    private func setToolBar() {
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(self.view)
        }
        //创建一个tabbarButton
        var items = [UIBarButtonItem]()
        //添加图片数组
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName":"selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName":"selectEmoticonKeyboard"],
            ["imageName": "compose_add_background"]]
        //遍历添加barbutton
        for item in itemSettings {
            let imageName = item["imageName"]
            let btn = UIButton(imageName: nil, backImageName: imageName!)
            if let action = item["actionName"] {
                btn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside)
            }
            let barBtn = UIBarButtonItem(customView: btn)
            items.append(barBtn)
            let spaceBar = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(spaceBar)
        }
        items.removeLast()
        toolBar.items = items
        
    }
    //改变键盘的方法
    @objc func keyboardWillChange(n:NSNotification) {
        print(n)
        //动画时间
        let duration = (n.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue;
        //endCGRect//转换成cgrect类型
        let endCGRect = (n.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).CGRectValue();
        let curve = (n.userInfo!["UIKeyboardAnimationCurveUserInfoKey"] as! NSNumber).integerValue
        //获取要偏移的距离
        let offsetY = -screenHeight + endCGRect.origin.y
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(offsetY)
        }
        
        //添加动画来强制刷新
        UIView.animateWithDuration(duration) { () -> Void in
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
        
    }
    //创建通知来改变toolBar的位置
    private func registerNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    
 
    //设置文本内容
    private func setTextView(){
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.left.top.right.equalTo(view)
            make.height.equalTo(screenHeight / 3)
        }
        textView.addSubview(placeLabel)
        placeLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(8)
            make.left.equalTo(5)
        }
    }
    //设置navbar
    private func setNav(){
        //添加左右的视图
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .Plain, target: self, action: "send")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        //让发送按钮失去交互
        self.navigationItem.rightBarButtonItem?.enabled = false
        //添加自定义的控件视图
        let titleView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        //添加nav的属性
        navigationItem.titleView = titleView
        //添加自定义的label
        let titleLabel:UILabel = UILabel(content: "发微博", color: UIColor.darkGrayColor(), fontSize: 17)
        let nameLabel:UILabel = UILabel(content: UserAccontViewMedol().userName ?? "", color: UIColor.lightGrayColor(), fontSize: 14)
        //添加控件
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        //设置约束
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.top.equalTo(titleView.snp_top)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(titleView.snp_centerX)
            make.bottom.equalTo(titleView.snp_bottom)
        }
        
    }
}
